package pers.liyan.shi.computermanager.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import pers.liyan.shi.computermanager.core.Result;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.List;

/**
 * @author ShiLY
 * @version 1.0
 * @date 2020/9/5 20:21
 */
@Slf4j
@Component
public class SystemUtil {


    @Autowired
    private Environment environment;

    private List<String> activeProfiles;

    @PostConstruct
    private void init() {
        log.info("SystemUtil init...");
        activeProfiles = Arrays.asList(environment.getActiveProfiles());
        log.info("SystemUtil init finish activeProfiles: {}", activeProfiles);
    }

    /**
     * 执行命令
     */
    public String execCmdRtString(String cmd) {
        log.info("execCmd: {}", cmd);

        if (activeProfiles.contains("mock")) {
            return Result.OK_CODE_STR;
        }

        try {
            Runtime runtime = Runtime.getRuntime();
            runtime.exec(cmd);
            return Result.OK_CODE_STR;
        } catch (Exception e) {
            return e.getMessage();
        }

    }

    /**
     * 执行命令
     */
    public Result execCmdRtResult(String cmd) {
        log.info("execCmd: {}", cmd);
        if (activeProfiles.contains("mock")) {
            return Result.ok();
        }

        try {
            Runtime runtime = Runtime.getRuntime();
            runtime.exec(cmd);
            return Result.ok();
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
    }

}
